include Makefile.testcase 
.PHONY: clean

CROSS_COMPILE := mips-sde-elf-
SRC_DIR := ./src/
BUILD_DIR := ./build/

DEBUG := false

CC :=  $(CROSS_COMPILE)gcc
AS := $(CROSS_COMPILE)as
LD := $(CROSS_COMPILE)ld
OBJCOPY := $(CROSS_COMPILE)objcopy
OBJDUMP := $(CROSS_COMPILE)objdump

CFLAGS := -mips1 -EL

ifeq ($(DEBUG), true)
CFLAGS += -g
endif

USER_PROGRAM_DIR := $(BUILD_DIR)$(USER_PROGRAM)/
OBJECTS := $(USER_PROGRAM_DIR)$(USER_PROGRAM).o

default: c
c: hello clean compile_c assembly convert bin generate_coe
asm: clean compile_asm assembly convert bin generate_coe

hello:
	@echo making... 使用的程序为 : $(USER_PROGRAM)

clean:
	@echo 第一步:清除build
	@echo 清除$(wildcard ./build/$(USER_PROGRAM))
ifeq ($(BUILD_DIR)$(USER_PROGRAM),$(wildcard ./build/$(USER_PROGRAM)))
	rm -r ./build/$(USER_PROGRAM)
else
	@echo 没有找到对应的文件目录
endif
	mkdir $(BUILD_DIR)$(USER_PROGRAM)

compile_c: $(SRC_DIR)$(USER_PROGRAM).c
	$(CC) -S -mips1 $(SRC_DIR)$(USER_PROGRAM).c -o $(USER_PROGRAM_DIR)$(USER_PROGRAM).S

compile_asm: $(SRC_DIR)$(USER_PROGRAM).S
	@cp  $(SRC_DIR)$(USER_PROGRAM).S $(USER_PROGRAM_DIR)

assembly: 
	$(CC) $(CFLAGS) -c $(USER_PROGRAM_DIR)$(USER_PROGRAM).S -o $(USER_PROGRAM_DIR)$(USER_PROGRAM).o
	$(LD) -T default.ld $(CFLAGS) $(OBJECTS) -o $(USER_PROGRAM_DIR)$(USER_PROGRAM)
	$(OBJDUMP) -alD $(USER_PROGRAM_DIR)$(USER_PROGRAM) > $(USER_PROGRAM_DIR)$(USER_PROGRAM).asm

convert: convert.c
	gcc $< -o $@

bin: inst.bin data.bin

inst.bin: $(USER_PROGRAM_DIR)$(USER_PROGRAM)
	$(OBJCOPY) -O binary -j .text $<  $(USER_PROGRAM_DIR)$@

data.bin: $(USER_PROGRAM_DIR)$(USER_PROGRAM)
	$(OBJCOPY) -O binary -j .data $<  $(USER_PROGRAM_DIR)$@

generate_coe:
	@./convert $(USER_PROGRAM_DIR)inst.bin $(USER_PROGRAM_DIR)data.bin
	@mv inst_rom.coe $(USER_PROGRAM_DIR)$(USER_PROGRAM)_inst.coe
	@mv data_ram.coe $(USER_PROGRAM_DIR)$(USER_PROGRAM)_data.coe
	@rm $(USER_PROGRAM_DIR)data.bin $(USER_PROGRAM_DIR)inst.bin 
	@rm $(USER_PROGRAM_DIR)$(USER_PROGRAM)  $(USER_PROGRAM_DIR)$(USER_PROGRAM).o